<script setup lang="ts">
defineOptions({
  name: "fabBoardElectricity"
});

import { ref, nextTick, inject } from "vue";
import fabBoardModelBox from "../fabBoardModelBox.vue";
import fabBoardEchartsModelBoxItem from "../fabBoardEchartsModelBoxItem.vue";
import { spcquerySpcAnalysis } from "@/api/spc";
import { getFabBoardPieData, getFabBoardBarData } from "@/api/modules/fab";
import dayjs from "dayjs";

const configOptions = inject("configOptions", ref<Array<any>>([]));

const emitBoardAreaEventCb = inject("emitBoardAreaEvent") as Function;

const title = ref<string>("电科关注指标");
const area = ref<string>("");
const loading = ref<boolean>(false);
const electricityData = ref<Array<Record<string, any>>>([]);
const target = ref<string>("");
const target_2 = ref<string>("");
const target_3 = ref<Array<string>>([]);
const barMaterialCode = ref<string>("");
const barAreaCode = ref<string>("");

const electricityConsumptionAreaRef = ref<InstanceType<typeof fabBoardEchartsModelBoxItem> | null>(null);
const electricityConsumptionFabRef = ref<InstanceType<typeof fabBoardEchartsModelBoxItem> | null>(null);
const electricityVoltageRef = ref<InstanceType<typeof fabBoardEchartsModelBoxItem> | null>(null);
const electricityCurrentRef = ref<InstanceType<typeof fabBoardEchartsModelBoxItem> | null>(null);

const electricityConsumptionAreaData = ref<Record<string, any> | null>(null);
const electricityConsumptionFabData = ref<Record<string, any> | null>(null);
const electricityVoltageData = ref<Record<string, any> | null>(null);
const electricityCurrentData = ref<Record<string, any> | null>(null);

const electricityConsumptionAreaTitle = ref<string>("今日用电区域占比（%）");
const electricityConsumptionAreaDialogTitle = ref<string>("今日机台总用电区域统计（kW/h）");
const electricityConsumptionFabTitle = ref<string>("机台总用电统计（kW/h）");
const electricityVoltageTitle = ref<string>("机台电压变化情况（V）");
const electricityCurrentTitle = ref<string>("机台电流变化情况（A）");

const mapConfigOptionsFn = (val: string) => {
  const c = configOptions.value.find(item => item.className === "ELECTRICTITY" && item.chartType === "pie");
  const d = configOptions.value.find(item => item.className === "ELECTRICTITY" && item.chartType === "column" && item.areaId === val);
  const e = configOptions.value.filter(item => item.className === "ELECTRICTITY" && item.chartType === "spc" && item.areaId === val);
  target.value = c?.quotaCode;
  target_2.value = d?.quotaCode;
  target_3.value = e?.map(item => item?.quotaCode);
  return !e?.length;
};

const areaChangeHandler = async (val: string, flag: boolean = false) => {
  emitBoardAreaEventCb("electrictity", val);

  electricityConsumptionAreaData.value = null;
  electricityConsumptionFabData.value = null;
  electricityVoltageData.value = null;
  electricityCurrentData.value = null;
  const flag2 = mapConfigOptionsFn(val);
  barMaterialCode.value = target_2.value;
  barAreaCode.value = area.value === "ALL" ? null : area.value;
  await init(flag, flag2);
};

const startLoading = () => {
  loading.value = true;
};

const closeLoading = () => {
  loading.value = false;
};

// 请求饼图数据
const queryPieDataFn = async (cb?: (flag?: boolean) => void) => {
  if (!target.value) return cb && cb();
  const params = { materialCode: target.value };
  electricityConsumptionAreaRef.value.loading = true;
  const res = await getFabBoardPieData(params, () => {
    closeLoading();
    electricityConsumptionAreaRef.value.loading = false;
  });
  electricityConsumptionAreaData.value = res;
  cb && cb(true);
};

// 请求柱状图数据
const queryBarDataFn = async (cb?: (flag?: boolean) => void) => {
  if (!target_2.value) return cb && cb();
  const areaCode = area.value === "ALL" ? null : area.value;
  const params = { materialCode: target_2.value, areaCode };
  electricityConsumptionFabRef.value.loading = true;
  const res = await getFabBoardBarData(params, () => {
    closeLoading();
    electricityConsumptionFabRef.value.loading = false;
  });
  electricityConsumptionFabData.value = res;
  cb && cb(true);
};

const getLineParams = () => {
  const startTime = dayjs().startOf("day").format("YYYY-MM-DD HH:mm:ss");
  const endTime = dayjs().format("YYYY-MM-DD HH:mm:ss");
  const timePeriod = "minutes";
  // 调试
  // const timePeriod = "hour";
  const jobIdList = null;
  const pointList = [...target_3.value];
  return { startTime, endTime, timePeriod, jobIdList, pointList };
};

// 请求折现图数据
const queryLineDataFn = async (cb?: () => void) => {
  const params = getLineParams();
  electricityVoltageRef.value.loading = true;
  electricityCurrentRef.value.loading = true;
  const res = await spcquerySpcAnalysis(params, () => {
    closeLoading();
    electricityVoltageRef.value.loading = false;
    electricityCurrentRef.value.loading = false;
  });
  electricityData.value = res;
  for (const d of res) {
    switch (d.point) {
      case target_3.value[0]:
        electricityVoltageData.value = d;
        break;
      case target_3.value[1]:
        electricityCurrentData.value = d;
        break;
    }
  }
  cb && cb();
};

const init = async (flag: boolean = false, flag2: boolean = false) => {
  startLoading();
  queryPieDataFn(async (flag: boolean) => {
    if (flag) {
      await nextTick();
      electricityConsumptionAreaRef.value?.init(flag);
    } else {
      await nextTick();
      electricityConsumptionAreaRef.value?.removeEcharts();
    }
  });
  queryBarDataFn(async (flag: boolean) => {
    if (flag) {
      await nextTick();
      electricityConsumptionFabRef.value?.init(flag);
    } else {
      await nextTick();
      electricityConsumptionFabRef.value?.removeEcharts();
    }
  });
  if (!flag2) {
    queryLineDataFn(async () => {
      await nextTick();
      electricityVoltageRef.value?.init(flag);
      electricityCurrentRef.value?.init(flag);
    });
  } else {
    await nextTick();
    electricityVoltageRef.value?.init(flag);
    electricityCurrentRef.value?.init(flag);
  }
  closeLoading();
};
</script>

<template>
  <fabBoardModelBox v-model="area" v-model:loading="loading" :title="title" @change="areaChangeHandler">
    <div class="electrictity-content">
      <fabBoardEchartsModelBoxItem
        ref="electricityConsumptionAreaRef"
        exportImage
        echartsType="pie"
        eventType="areaCode"
        unit="kW/h"
        :materialCode="target"
        :dialogTitle="electricityConsumptionAreaDialogTitle"
        :title="electricityConsumptionAreaTitle"
        :data="electricityConsumptionAreaData"
      />
      <fabBoardEchartsModelBoxItem
        ref="electricityConsumptionFabRef"
        exportImage
        echartsType="bar"
        :materialCode="barMaterialCode"
        :areaCode="barAreaCode"
        :title="electricityConsumptionFabTitle"
        :data="electricityConsumptionFabData"
      />
      <fabBoardEchartsModelBoxItem ref="electricityVoltageRef" exportImage :title="electricityVoltageTitle" :data="electricityVoltageData" />
      <fabBoardEchartsModelBoxItem ref="electricityCurrentRef" exportImage :title="electricityCurrentTitle" :data="electricityCurrentData" />
    </div>
  </fabBoardModelBox>
</template>

<style lang="scss" scoped>
.electrictity-content {
  display: grid;
  grid-template-rows: repeat(1, 100%);
  grid-template-columns: repeat(4, 1fr);
  gap: 8px;
  width: 100%;
  height: 100%;
}
</style>
